package com.boomsecret.concurrent;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by wangjinliang on 2018/1/23.
 */
public class CyclicBarrierDemo {

    private static final int CYCLIC_BARRIER_COUNT = 2;
    private static final int THREAD_COUNT = 4;

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(CYCLIC_BARRIER_COUNT, ()->{
            System.out.println("达到临界点");
        });

        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);
        for (int index = 0; index < THREAD_COUNT; index ++) {
            executorService.execute(()->{
                try {
                    System.out.println("ThreadId:" + Thread.currentThread().getId());
                    Thread.sleep(2000);
                    int await = cyclicBarrier.await();
                    System.out.println("await:" + await);
                    System.out.println("ThreadId:" + Thread.currentThread().getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        executorService.shutdown();
    }
}
